package app

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type Param struct {
}

type Api struct {
	URL    string              `json:"url"`
	Method string              `json:"method"`
	Header []map[string]string `json:"header"`
	Query  []map[string]string `json:"query"`
	Body   []map[string]string `json:"body"`
}

func (api *Api) Run() (string, error) {
	client := &http.Client{}
	var body *bytes.Buffer
	if api.Body != nil {
		var param = make(map[string]interface{})
		for _, value := range api.Body {
			param[value["k"]] = value["v"]
		}
		js, err := json.MarshalIndent(&param, "", "\t")
		if err != nil {
			fmt.Printf("analysis param failed, err:%v\n\n", err)
			return "", err
		}
		body = bytes.NewBuffer(js)
	}
	if body == nil {
		b := []byte("")
		body = bytes.NewBuffer(b)
	}

	req, err := http.NewRequest(api.Method, api.URL, body)
	if err != nil {
		fmt.Printf("init http request failed, err:%v\n\n", err)
		return "", err
	}

	if api.Header != nil {
		for _, value := range api.Header {
			req.Header.Add(value["k"], value["v"])
		}
	}

	if api.Query != nil {
		q := req.URL.Query()
		for _, value := range api.Query {
			q.Add(value["k"], value["v"])
		}
		req.URL.RawQuery = q.Encode()
	}

	resp, _ := client.Do(req)
	defer resp.Body.Close()
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get response failed,err:%v\n\n", err)
		return "", err
	}
	return string(b), nil
}
